from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent,AgentExecutor
from langchain_core.tools import tool
from langchain import hub
import random
from langchain_core.prompts import PromptTemplate
from langchain.tools.render import render_text_description
from langchain.agents.output_parsers import ReActSingleInputOutputParser
from langchain.agents.format_scratchpad import format_log_to_str


api_key = "sk-6S0PtpNia71gjcfwSsDPsJ9mGqsVPr2XRQzAx1dHbJS7RW4t"
api_base="https://chatapi.littlewheat.com/v1"

llm = ChatOpenAI(model="gpt-3.5-turbo",api_key=api_key ,base_url=api_base)

prompt = hub.pull("hwchase17/react")
print(prompt.pretty_print())
prompt_str= """
Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}
"""
promptTemplate = PromptTemplate.from_template(prompt_str)

@tool
def getWeather(loc):
    """
        查询即时天气函数
        :param loc: 必要参数，字符串类型，用于表示查询天气的具体城市名称，\
        注意，中国的城市需要用对应城市的英文名称代替，例如如果需要查询上海市天气，则loc参数需要输入'ShangHai'；
        :return：OpenWeather API查询即时天气的结果，具体URL请求地址为：https://api.openweathermap.org/data/2.5/weather\
        返回结果对象类型为解析之后的JSON格式对象，并用字符串形式进行表示，其中包含了全部重要的天气信息
    """
    temp=random.randint(20,35)
    data = loc+"的当前气温是"+str(temp)
    return data

tools = [getWeather]

finalPrompt = promptTemplate.partial(tools=render_text_description(list(tools)),
                                     tool_names=", ".join([t.name for t in tools]))

llm_with_stop=llm.bind(stop=["\nObservation"])

output_parser = ReActSingleInputOutputParser()

agent = ({
    "input":lambda x:x["input"],
    "agent_scratchpad":lambda x:format_log_to_str(x["intermediate_steps"])
} | finalPrompt | llm_with_stop | output_parser)

agentExecutor = AgentExecutor(agent=agent,tools=tools,verbose=True)
response = agentExecutor.invoke({"input": "北京和大理今天的气温差距多大？"})
print(response)